<?php
abstract class AbstractMessage extends MessagesAppModel {

	var $name = 'Message';
	var $useTable = 'messages';
	var $validate = array(
		'subject' => VALID_NOT_EMPTY,
		'message' => VALID_NOT_EMPTY,
		'sender_id' => VALID_NOT_EMPTY,
		'recipient_id' => VALID_NOT_EMPTY
	);
	var $hasOne = array('Attachment'=>array('className'=>'Messages.Attachment'));
	var $belongsTo = array(
			'Thread' => array('className'=>'Messages.Thread')

	);
	
	var $additionalFields = array(
					'sender_email',
					'recipient_email',
					'sender_username',
					'recipient_username',
				);
	var $cacheFields = array('sender_email'=>'onUpdate','recipient_email'=>"onUpdate",'senser_username'=>"onUpdate",'recipient_username'=>"onUpdate");
	var $fieldProperties = array(
		'subject' => array('group'=>'send'),
		'body' => array('label'=>'Message','group'=>'send'),
	);
	
	function beforeSave($options)
	{
		parent::beforeSave($options);
		if(!isset($this->data['Message']['id']) && $this->id == null && empty($this->data['Message']['thread_id']))
		{
			$this->Thread->save(array('Thread'=>array('creator'=>$this->data['Message']['sender_type'],'creator_id'=>$this->data['Message']['sender_id'])));
			$this->data['Message']['thread_id'] = $this->Thread->getLastInsertID();
		}
		return true;
	}
	
	function sender_email($result)
	{
		return $this->getOwnerInfo($result,'sender','email');
	}
	
	function recipient_email($result)
	{
		return $this->getOwnerInfo($result,'recipient','email');
	}
	
	function sender_username($result)
	{
		return $this->getOwnerInfo($result,'sender','username');
	}
	
	function recipient_username($result)
	{
		return $this->getOwnerInfo($result,'recipient','username');
				
	}
	
	function getOwnerInfo($result,$userRole = "sender",$field="email")
	{
		if(!isset($result['Message'][$userRole.'_type']) || !isset($result['Message'][$userRole.'_id']))
		{
			return;
		}
		$ownerId = $result['Message'][$userRole.'_id'];
		$ownerType = Inflector::camelize($result['Message'][$userRole.'_type']);
		if(property_exists($this,$ownerType) == false || !is_object($this->{$ownerType}))
		{
			$this->{$ownerType} = Utility::getModelObject($ownerType);
		}
		$result;
		if($this->{$ownerType}->hasField($field) == true)
		{
			$result = $this->{$ownerType}->field($field,array('id'=>$ownerId));
		}		
		return $result;	
	}
}
?>